package com.itboye.ihomebank.base;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.interfaces.IRefreshAfterAlert;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.LoadingDialog;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.UIAlertView;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Observer;

/**
 * 继承自该Fragment的类不需要findViewById，在onActivityCreated中调用super.onActivityCreated()
 * 后即可直接使用全局的控件了
 *
 * @author Mr.w
 */
public abstract class BaseFragment extends Fragment implements Observer {
    LoadingDialog progressDialog = null;
    UserPresenter userPresenter;
    IRefreshAfterAlert ref;
    String username;
    String password;
    UIAlertView   uiAlertView;
    //	private PushAgent mPushAgent;
    public static final String EVENT_TYPE_UNKNOWN = BaseOtherActivity.class
            .getName() + "_unknown";

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//		mPushAgent = PushAgent.getInstance(getActivity());
//		mPushAgent.enable();
//		mPushAgent.onAppStart();
        smartInject(getView());
        username=SPUtils.get(getActivity(), null, SPContants.MOBILE, "") + "";
        password=SPUtils.get(getActivity(), null, SPContants.MOBILE_PASS, "") + "";
        userPresenter=new UserPresenter(this);
        progressDialog = new LoadingDialog();
        onMyActivityCreated();
    }


    @Override
    public void onResume() {
        super.onResume();
//		MobclickAgent.onResume(getActivity());
    }


    @Override
    public void onPause() {
        super.onPause();
//		MobclickAgent.onPause(getActivity());
    }

    protected void smartInject(View view) {
        try {
            Class<? extends Fragment> clz = getClass();
            while (clz != BaseFragment.class) {
                Field[] fs = clz.getDeclaredFields();
                Resources res = getResources();
                String packageName = getActivity().getPackageName();
                for (Field field : fs) {
                    if (!View.class.isAssignableFrom(field.getType())) {
                        continue;
                    }
                    int viewId = res.getIdentifier(field.getName(), "id",
                            packageName);
                    if (viewId == 0)
                        continue;
                    field.setAccessible(true);
                    try {
                        View v = view.findViewById(viewId);
                        field.set(this, v);
                        Class<?> c = field.getType();
                        Method m = c.getMethod("setOnClickListener",
                                android.view.View.OnClickListener.class);
                        m.invoke(v, this);
                    } catch (Throwable e) {
                    }
                    field.setAccessible(false);

                }

                clz = (Class<? extends Fragment>) clz.getSuperclass();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * @param data
     * @return 2016-4-23 hebidu
     */
    public ResultEntity handlerError(Object data) {
        ResultEntity result = (ResultEntity) data;
        if (result == null) {
            result = new ResultEntity("-1", "数据格式错误!~", data);
            return result;
        }

//        if (result.hasError()) {
//
//            if (result.getMsg().contains("java.net.UnknownHostException")) {
//                ByAlert.alert("请连接网络 ");
//            } else {
////                ByAlert.alert(result.getMsg());
//            }
//            result.setEventType(EVENT_TYPE_UNKNOWN);
//            return result;
//        }

        return result;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(initView(), null);
    }

    public abstract int initView();

    public abstract void onMyActivityCreated();

    /**
     * 显示进度对话框,带有消息 flag 是否可以取消
     */
    @SuppressLint("NewApi")
    public void showProgressDialog(String message, boolean flag) {
        if (progressDialog == null)
            return;
        setProgressDialogMessage(message);
        if (progressDialog.isAdded()) {

        }else {
            progressDialog.show(getActivity().getFragmentManager(), message);
            progressDialog.setCancelable(flag);
        }

    }

    /**
     * 设置进度对话框消息
     *
     * @param message
     */
    public void setProgressDialogMessage(String message) {
        progressDialog.setMsg(message);
    }

    /**
     * 关闭进度对话框
     */
    @SuppressLint("NewApi")
    public void closeProgressDialog() {
        if (progressDialog != null) {
            if (progressDialog.getDialog().isShowing()) {
                progressDialog.dismiss();
            }
        }
    }

    public String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;

            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        return false;
    }

    /**
     * 设置状态栏高度
     * @param
     */
    public void setStatusBarHeight(View view) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ //是否大于6.0 大于6.0可以沉浸式 小于不行
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.height = getStatusBarHeight();
            view.setLayoutParams(params);

    }
    /**
     * 获取状态栏高度
     * @return
     */
    public int getStatusBarHeight() {
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            return getResources().getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    /**
     * 设置状态栏颜色，
     * @param color 颜色资源id， 如 R.color.orange</br> 0 黑色
     */
    protected void setStatusBarColor(View view,int color) {
                                  //Build.VERSION_CODES.LOLLIPOP 5.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //大于4.4
                view.setBackgroundColor(color);
        }
    }

    //加载弹框 切换锁服务器
    public void showAlert(){
//        String o = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.LOCK_SESSION, "");
//        if ("".equals(o)){

            if (uiAlertView==null){
                uiAlertView = new UIAlertView(getActivity(), "温馨提示","服务器出小差了,重新尝试连接", "确定", "取消");
            }
            uiAlertView.show();
            uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                @Override
                public void doLeft() {
                    //获取sid 替换uid
                    userPresenter.getSid(username,password);
                    uiAlertView.dismiss();
                    uiAlertView=null;
                }

                @Override
                public void doRight() {
                    uiAlertView.dismiss();
                    uiAlertView=null;
                }
            });
//        }
    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity!=null){
            if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
    }
}
